package com.example.springboot08shiro2.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 在这里将网页的请求导向合适的html, 也可以为html中指向的地址分配另一个html
 */
@Controller
public class MyController {
    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello, shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }
    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }
    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }
    //tologin那个页面点提交的时候, 会把username和password提交给这个页面,
    //这个/login是需要响应的url, return的login是要被封装成login.html的前端页面
    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据, 加密
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);//固定代码, 登录就这样, 无异常则ok
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名错误");
            //e.printStackTrace();
            return "login";
        } catch (IncorrectCredentialsException e){
            model.addAttribute("msg", "密码不存在");
            return "login";
        }
    }
    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问";
    }
}
